package com.xqc.shop.account.service.impl;

import java.util.HashMap;
import java.util.Map;

import com.xqc.shop.account.manager.UserAccountManager;
import com.xqc.shop.order.bean.EoOrderBean;
import com.xqc.shop.order.service.EoOrderService;

import com.xqc.shop.stock.service.EoStockService;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.xqc.shop.account.api.UserAccountService;
import com.xqc.shop.account.model.UserAccountModel;

@Service
public class UserAccountServiceImpl implements UserAccountService{

	private static final Logger logger = LoggerFactory.getLogger(UserAccountServiceImpl.class);
	@Autowired
	private UserAccountManager userAccountManager;
	@Autowired
	private RedisTemplate<String, Object> redisTemplate;
	@Autowired
	private EoOrderService eoOrderService;
	@Autowired
	private EoStockService eoStockService;
	
	@Override
	public Object getIp() {
		Map<String,String> dataMap = new HashMap<>();
		dataMap.put("IP", "localhost");
		dataMap.put("PORT", "7003");
		dataMap.put("REMARK", "测试7003");
		return dataMap;
	}

	@Override
	public boolean updateMoney(Integer userId) {
		UserAccountModel accountModel = new UserAccountModel();
		return this.userAccountManager.insert(accountModel) ;
	}

	@Override
	@GlobalTransactional(name = "shop_tx_group",rollbackFor = Exception.class)
	public boolean createOrder() {
		logger.info("分布式事务全局唯一ID:"+ RootContext.getXID());
		//创建订单
		EoOrderBean eoOrderBean = new EoOrderBean();
		eoOrderBean.setStockId(1L);
		eoOrderBean.setUserId(1L);
		logger.info("创建订单开始");
		this.eoOrderService.insert(eoOrderBean);
		logger.info("创建订单结束");

		//扣减库存
		logger.info("扣减库存结束");
		this.eoStockService.updateStock(1);
		logger.info("扣减库存结束");

		//扣减账户余额
		logger.info("扣减余额开始");
		boolean updateMoney = this.userAccountManager.updateMoney(1);
		logger.info("扣减余额结束");

		return updateMoney;
	}
	
}
